import React from "react";

// 导入组件样式
import "./index.css";

class Comment extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      comments: [
        // { id: 1, name: "小红", comment: "多关照!" },
        // { id: 2, name: "小明", comment: "我是新来的!" },
      ],
      // 评论人
      name: '',
      // 评论内容
      comment: ''
    };
  }

  renderList = () => {
    return this.state.comments.length === 0 ? (
      <div className="nodata">暂无评论！快去评论吧</div>
    ) : (
      <ul className="list">
        {this.state.comments.map((item) => {
          return (
            <li key={item.id}>
              <p className="p-line">{item.name}</p>
              <p>{item.comment}</p>
            </li>
          );
        })}
      </ul>
    )
  }

  handleName = (e) => {
    this.setState({
      name: e.target.value
    })
  }
  handleComment = (e) => {
    this.setState({
      comment: e.target.value
    })
  }
  handleSubmit = () => {
    if(this.state.name.trim().length === 0 || this.state.comment.trim().length === 0){
      alert('请输入评论人和评论内容')
      return;
      // 上面的写法和下面的写法等价
      // return alert('请输入评论用户或评论内容')
    }
    console.log(this.state.name, this.state.comment)
    const comment = {
      id: Math.random(),
      name: this.state.name,
      comment: this.state.comment
    }
    console.log(comment)
    const newComments = [...this.state.comments, comment]
    this.setState({
      comments: newComments,
      name:'',
      comment:''
    })
    
    // 或者下面这种写法，alert之后不用return
    // if(this.state.name.trim().length === 0 || this.state.comment.trim().length === 0){
    //   alert('请输入评论人和评论内容')
    // }else{
    //   // 正常处理数据
    // }
    // push方式
    // const newComments = this.state.comments
    // newComments.push(comment)
    // this.setState({
    //   comments: newComments,
    //   name:'',
    //   comment:''
    // })
  }

  render() {
    console.log(this.state)
    return (
      <div className="box">
        <h1>评论</h1>
        {/* 发表评论 */}
        <div>
          <p>
            <input type="text" value={this.state.name} onChange={this.handleName} placeholder="请输入评论人" />
          </p>
          <p>
            <textarea type="text" value={this.state.comment} onChange={this.handleComment} placeholder="请输入评论内容" />
          </p>
          <p>
            <button className="btn" onClick={this.handleSubmit}>发表评论</button>
          </p>
        </div>
        {/* 评论列表 */}
        <hr className="line" />
        {this.renderList()}


      </div>
    );
  }
}

export default Comment;
